import wxRequest from "./request"
import { clearStorage, getStorage } from './storage'
import { modal, model, toast } from './extendAPI'
import { env } from './env'
// 实例化请求
const instance = new wxRequest({
    baseURL: env.baseURL,
    timeout: 15000
})

//配置请求拦截器
instance.interceptors.request = (config) => {
    // 在发送请求之前判断本地是否存在访问令牌Token
    // 如果token存在就添加到请求头中
    const token = getStorage('token')
    if (token) {
        config.header['token'] = token
    }
    return config
}
//配置相应拦截器
instance.interceptors.response = async (response) => {
    const { isSuccess, data } = response
    if (!isSuccess) {
        wx.showToast({
            title: '网络请求异常',
            icon: 'error'
        })
        return response
    }
    //判断服务响应的业务状态码
    switch (data.code) {
        case 200:
            return data
        case 208:
            console.log('清除token');
            clearStorage()
            wx.navigateTo({
                url: '/pages/login/login'
            })
            const res = await model({
                content: '鉴权失败，请重新登录',
                showCancel: false //不显示取消按钮
            })

            return Promise.reject(response)
        default:
            toast({
                title: '程序出现异常，请联系客服或稍后重试'
            })
    }
    return data

}
export default instance